package com.example.coupon.serialization;

import com.alibaba.fastjson.JSON;
import com.example.coupon.entity.Coupon;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * 优惠券实体类自定义序列化器
 * @author wangbo
 * @description:
 * @date 2021/2/199:58
 */
public class CouponSerialize extends JsonSerializer<Coupon> {

    @Override
    public void serialize(Coupon coupon, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException {
        //开始序列化
        generator.writeStartObject();

        generator.writeStringField("id",coupon.getId().toString());
        generator.writeStringField("templateId",coupon.getTemplateId().toString());
        generator.writeStringField("userId",coupon.getUserId().toString());
        generator.writeStringField("couponCode",coupon.getCouponCode());
        generator.writeStringField("assignTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(coupon.getAssignTime()));
        generator.writeStringField("name",coupon.getCouponTemplateSDK().getName());
        generator.writeStringField("logo",coupon.getCouponTemplateSDK().getLogo());
        generator.writeStringField("desc",coupon.getCouponTemplateSDK().getDesc());
        generator.writeStringField("expiration", JSON.toJSONString(coupon.getCouponTemplateSDK().getTemplateRule().getExpiration()));
        generator.writeStringField("discount",JSON.toJSONString(coupon.getCouponTemplateSDK().getTemplateRule().getDiscount()));
        generator.writeStringField("usage",JSON.toJSONString(coupon.getCouponTemplateSDK().getTemplateRule().getUsage()));

        generator.writeEndObject();


    }
}
